package com.iot.ammeter.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toolbar
import androidx.activity.viewModels
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.iot.ammeter.R
import com.iot.ammeter.databinding.ActivityMainBinding
import com.iot.ammeter.view.fragments.MyDeviceFragment
import com.iot.ammeter.view.fragments.UserCenterFragment
import com.iot.ammeter.viewmodel.MainViewModel

data class TabPageInfoRes(val itemName: Int, val pageTitle: Int, val pageFragment: Class<*>)

val pages = arrayOf(
    TabPageInfoRes(R.string.my_device, R.string.my_device_title, MyDeviceFragment::class.java),
    TabPageInfoRes(R.string.user_center, R.string.user_center_title, UserCenterFragment::class.java),
)

/**
 * 实现了 [TabLayout.OnTabSelectedListener] 接口来注册 [TabLayout] 的切换事件
 */
class MainActivity : AppCompatActivity(), TabLayout.OnTabSelectedListener {

    private lateinit var viewBinding: ActivityMainBinding
    private lateinit var toolbar: Toolbar
    private val mainViewModel by viewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        // inflate view binding
        viewBinding = ActivityMainBinding.inflate(layoutInflater)
        // set view by view binding
        setContentView(viewBinding.root)

        toolbar = viewBinding.toolbar

        val tabLayout = viewBinding.mainTabLayout.apply {
            addOnTabSelectedListener(this@MainActivity)
        }

        val viewPager = viewBinding.mainViewPager.apply {
            adapter = MainPager2Adapter(this@MainActivity)
        }

        // Associate tab and pager2
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = getString(pages[position].itemName)
        }.attach()

    }

    /**
     * Called when a tab enters the selected state.
     * 更改 toolbar 标题
     */
    override fun onTabSelected(tab: TabLayout.Tab) {
        toolbar.title = getString(pages[tab.position].pageTitle)
    }

    /**
     * Called when a tab exits the selected state.
     * 本项目中无实现
     */
    override fun onTabUnselected(tab: TabLayout.Tab) {
    }

    /**
     * Called when a tab that is already selected is chosen again by the user.
     * Some applications may use this action to return to the top level of a category.
     * 本项目中无实现
     */
    override fun onTabReselected(tab: TabLayout.Tab) {
    }

}

class MainPager2Adapter(fragment: FragmentActivity) : FragmentStateAdapter(fragment) {
    override fun getItemCount(): Int = pages.size

    override fun createFragment(position: Int): Fragment {
        return pages[position].pageFragment.newInstance() as Fragment
    }
}
